<template>
  <div class="question-manage">
    <h2>题目管理</h2>

    <!-- 搜索和操作区域 -->
    <div class="operation-bar">
      <el-button type="primary" @click="showAddDialog">
        <el-icon><Plus /></el-icon>添加题目
      </el-button>

      <div class="search-area">
        <!-- 专业选择器 -->
        <el-select
            v-model="filters.majorId"
            placeholder="选择专业"
            clearable
            style="width: 180px; margin-right: 10px;"
            @change="handleMajorChange"
        >
          <el-option
              v-for="major in majors"
              :key="major.majorId"
              :label="major.majorName"
              :value="major.majorId"
          />
        </el-select>

        <!-- 分类选择器 -->
        <el-select
            v-model="filters.categoryId"
            placeholder="选择分类"
            clearable
            style="width: 180px; margin-right: 10px;"
            @change="handleSearch"
            :disabled="!filters.majorId"
        >
          <el-option
              v-for="category in filteredCategories"
              :key="category.categoryId"
              :label="category.categoryName"
              :value="category.categoryId"
          />
        </el-select>

        <!-- 题目类型选择器 -->
        <el-select
            v-model="filters.questionType"
            placeholder="选择题型"
            clearable
            style="width: 120px; margin-right: 10px;"
            @change="handleSearch"
        >
          <el-option label="选择题" value="choice" />
          <el-option label="填空题" value="fill_in" />
        </el-select>

        <!-- 关键词搜索 -->
        <el-input
            v-model="filters.keyword"
            placeholder="搜索题目内容"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
            style="width: 300px; margin-right: 10px;margin-top: -2px;"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>
    </div>

    <!-- 题目列表 -->
    <el-table
        :data="questions"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
    >
      <!-- 序号列 -->
      <el-table-column label="序号" width="80" align="center">
        <template #default="{ $index }">
          {{ (pagination.currentPage - 1) * pagination.pageSize + $index + 1 }}
        </template>
      </el-table-column>

      <el-table-column label="题型" width="120" align="center">
        <template #default="{ row }">
          <el-tag :type="typeTagMap[row.questionType]">
            {{ typeMap[row.questionType] }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="题目内容" min-width="250">
        <template #default="{ row }">
          <div class="content-preview">{{ row.content }}</div>
        </template>
      </el-table-column>

      <el-table-column label="专业" min-width="180">
        <template #default="{ row }">
          <el-tag type="success">
            {{ row.majorName }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="分类" min-width="180">
        <template #default="{ row }">
          <el-tag type="info">
            {{ row.categoryName }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="creator" label="创建者" width="120" />

      <el-table-column label="分值/权重" width="120" align="center">
        <template #default="{ row }">
          <div>{{ row.baseScore }}分</div>
          <div style="font-size: 12px; color: #909399;">权重: {{ row.weight }}</div>
        </template>
      </el-table-column>

      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="220" fixed="right" align="center">
        <template #default="{ row }">
          <el-button
              type="primary"
              size="small"
              @click="showDetailDialog(row)"
          >详情</el-button>

          <el-button
              type="warning"
              size="small"
              @click="showEditDialog(row)"
          >编辑</el-button>

          <el-button
              type="danger"
              size="small"
              @click="handleDelete(row.questionId)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchQuestions"
          @current-change="fetchQuestions"
      />
    </div>

    <!-- 添加/编辑题目对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEditing ? '编辑题目' : '添加题目'"
        width="900px"
    >
      <el-form
          ref="questionForm"
          :model="formData"
          :rules="formRules"
          label-width="120px"
      >
        <!-- 专业选择器 -->
        <el-form-item label="专业" prop="majorId">
          <el-select
              v-model="formData.majorId"
              placeholder="请选择专业"
              style="width: 100%"
              @change="handleFormMajorChange"
          >
            <el-option
                v-for="major in majors"
                :key="major.majorId"
                :label="major.majorName"
                :value="major.majorId"
            />
          </el-select>
        </el-form-item>

        <!-- 分类选择器 -->
        <el-form-item label="分类" prop="categoryId">
          <el-select
              v-model="formData.categoryId"
              placeholder="请选择分类"
              style="width: 100%"
              :disabled="!formData.majorId"
          >
            <el-option
                v-for="category in formCategories"
                :key="category.categoryId"
                :label="category.categoryName"
                :value="category.categoryId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="题目类型" prop="questionType">
          <el-select
              v-model="formData.questionType"
              placeholder="请选择题型"
              style="width: 100%"
              :disabled="isEditing"
              @change="handleQuestionTypeChange"
          >
            <el-option label="选择题" value="choice" />
            <el-option label="填空题" value="fill_in" />
          </el-select>
        </el-form-item>

        <el-form-item label="题目内容" prop="content">
          <el-input
              v-model="formData.content"
              type="textarea"
              :rows="3"
              placeholder="请输入题目内容"
          />
        </el-form-item>

        <!-- 选择题选项区域 -->
        <div v-if="formData.questionType === 'choice'">
          <el-form-item
              v-for="(choice, index) in formData.choices"
              :key="`choice-${index}`"
              :label="`选项${index + 1}`"
              :prop="`choices.${index}.choiceContent`"
              :rules="{ required: true, message: '请输入选项内容', trigger: 'blur' }"
          >
            <div class="choice-item">
              <el-input
                  v-model="choice.choiceContent"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入选项内容"
                  class="choice-input"
              />
              <el-checkbox-group v-model="formData.answer" class="choice-actions">
                <el-checkbox :label="String.fromCharCode(65 + index)">正确答案</el-checkbox>
              </el-checkbox-group>
              <el-button
                  v-if="formData.choices.length > 2"
                  type="danger"
                  circle
                  @click="removeChoice(index)"
                  class="delete-btn"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="addChoice">
              <el-icon><Plus /></el-icon>添加选项
            </el-button>
            <span class="choice-count">
              当前选项数: {{ formData.choices.length }}
            </span>
          </el-form-item>
        </div>

        <!-- 填空题区域 -->
        <div v-else-if="formData.questionType === 'fill_in'">
          <el-form-item
              v-for="(blank, index) in formData.blanks"
              :key="`blank-${index}`"
              :label="`空位${index + 1}`"
          >
            <div class="blank-item">
              <el-input
                  v-model="blank.answer"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入答案"
                  class="blank-input"
              />
              <div class="max-length">
                <span>最大长度:</span>
                <el-input-number
                    v-model="blank.maxLength"
                    :min="1"
                    :max="500"
                    controls-position="right"
                />
              </div>
              <el-button
                  v-if="formData.blanks.length > 1"
                  type="danger"
                  circle
                  @click="removeBlank(index)"
                  class="delete-btn"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="addBlank">
              <el-icon><Plus /></el-icon>添加空位
            </el-button>
            <span class="blank-count">
              当前空位数: {{ formData.blanks.length }}
            </span>
          </el-form-item>
        </div>

        <el-form-item label="基础分数" prop="baseScore">
          <el-input-number
              v-model="formData.baseScore"
              :min="1"
              :max="100"
              controls-position="right"
          />
        </el-form-item>

        <el-form-item label="题目权重" prop="weight">
          <el-input-number
              v-model="formData.weight"
              :min="0.1"
              :max="5"
              :step="0.1"
              controls-position="right"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 题目详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="题目详情"
        width="800px"
    >
      <div class="question-detail">
        <div class="detail-row">
          <div class="detail-item">
            <span class="label">题目ID:</span>
            <span class="value">{{ currentQuestion.questionId }}</span>
          </div>
          <div class="detail-item">
            <span class="label">分类:</span>
            <span class="value">{{ currentQuestion.categoryName }}</span>
          </div>
          <div class="detail-item">
            <span class="label">所属专业:</span>
            <span class="value">{{ currentQuestion.majorName }}</span>
          </div>
        </div>

        <div class="detail-row">
          <div class="detail-item">
            <span class="label">基础分数:</span>
            <span class="value">{{ currentQuestion.baseScore }} 分</span>
          </div>
          <div class="detail-item">
            <span class="label">权重:</span>
            <span class="value">{{ currentQuestion.weight }}</span>
          </div>
          <div class="detail-item">
            <span class="label">收藏人数:</span>
            <span class="value">{{ currentQuestion.favoriteCount || 0 }}</span>
          </div>
        </div>

        <div class="detail-row">
          <div class="detail-item">
            <span class="label">总答题次数:</span>
            <span class="value">{{ currentQuestion.totalAttempts || 0 }}</span>
          </div>
          <div class="detail-item">
            <span class="label">正确次数:</span>
            <span class="value">{{ currentQuestion.correctAttempts || 0 }}</span>
          </div>
          <div class="detail-item">
            <span class="label">正确率:</span>
            <span class="value">{{ currentQuestion.correctRate || 0 }}%</span>
          </div>
        </div>

        <div class="detail-item">
          <span class="label">题型:</span>
          <el-tag :type="typeTagMap[currentQuestion.questionType]">
            {{ typeMap[currentQuestion.questionType] }}
          </el-tag>
        </div>

        <div class="detail-item">
          <span class="label">题目内容:</span>
          <div class="value content">{{ currentQuestion.content }}</div>
        </div>

        <div class="detail-item" v-if="currentQuestion.questionType === 'choice'">
          <span class="label">选项列表:</span>
          <div class="value">
            <div
                v-for="(choice, index) in currentQuestion.choices"
                :key="index"
                class="option-item"
            >
              <div>
<!--                选项前显示字母-->
<!--                <span class="option-letter">{{ String.fromCharCode(65 + index) }}. </span>-->
                {{ choice.choiceContent }}
              </div>
              <div class="option-tag">
                <el-tag :type="choice.isCorrect ? 'success' : 'info'" size="small">
                  {{ choice.isCorrect ? '正确答案' : '错误答案' }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>

        <div class="detail-item" v-if="currentQuestion.questionType === 'fill_in'">
          <span class="label">空位信息:</span>
          <div class="value">
            <div
                v-for="(blank, index) in currentQuestion.blanks"
                :key="index"
                class="blank-info"
            >
              <div>
                <span class="blank-label">空位 {{ index + 1 }}: </span>
                答案: {{ blank.answer }}
              </div>
              <div class="blank-tag">
                <el-tag size="small">最大长度: {{ blank.maxLength }}</el-tag>
              </div>
            </div>
          </div>
        </div>

        <div class="detail-row">
          <div class="detail-item">
            <span class="label">创建人:</span>
            <span class="value">{{ currentQuestion.creator }}</span>
          </div>
          <div class="detail-item">
            <span class="label">创建时间:</span>
            <span class="value">{{ formatDate(currentQuestion.createdAt) }}</span>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button type="primary" @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import axios from '@/api/server';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Search, Delete } from '@element-plus/icons-vue';
import { useUserStore } from '@/store/useUserstore';

const userStore = useUserStore();

// 题目列表数据
const questions = ref([]);
const loading = ref(false);
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

const filters = reactive({
  keyword: '',
  questionType: '',
  majorId: null,
  categoryId: null
});

// 专业数据
const majors = ref([]);
// 分类数据
const categories = ref([]);
// 表单分类数据
const formCategories = ref([]);

// 对话框控制
const dialogVisible = ref(false);
const detailDialogVisible = ref(false);
const isEditing = ref(false);

// 当前操作的题目
const currentQuestion = ref({});
const editingQuestionId = ref(null);

const formData = reactive({
  questionType: 'choice',
  content: '',
  answer: [],
  baseScore: 10,
  weight: 1.0,
  createdBy: null,
  majorId: null,
  categoryId: null,
  choices: [
    { choiceContent: '', isCorrect: false },
    { choiceContent: '', isCorrect: false }
  ],
  blanks: [
    { answer: '', maxLength: 20 }
  ]
});

// 表单验证规则
const formRules = reactive({
  majorId: [
    { required: true, message: '请选择专业', trigger: 'change' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  questionType: [
    { required: true, message: '请选择题目类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入题目内容', trigger: 'blur' },
    { min: 5, message: '题目内容至少5个字符', trigger: 'blur' }
  ],
  baseScore: [
    { required: true, message: '请输入基础分数', trigger: 'blur' }
  ],
  weight: [
    { required: true, message: '请输入权重', trigger: 'blur' }
  ],
  blanks: {
    validator: (rule, value, callback) => {
      if (formData.questionType === 'fill_in' &&
          formData.blanks.some(blank => !blank.answer)) {
        callback(new Error('所有空位必须填写答案'));
      } else {
        callback();
      }
    },
    trigger: 'blur'
  },
  answer: {
    validator: (rule, value, callback) => {
      if (formData.questionType === 'choice' && value.length === 0) {
        callback(new Error('请至少选择一个正确答案'));
      } else {
        callback();
      }
    },
    trigger: 'change'
  },
  'blanks.*.answer': {
    required: true,
    message: '请填写空位答案',
    trigger: 'blur'
  }
});

const loadInitialData = async () => {
  try {
    loading.value = true;

    // 并行加载专业和分类数据
    const [majorsRes, categoriesRes] = await Promise.all([
      axios.get('/admin/manage/majors'),
      axios.get('/admin/manage/categories')
    ]);

    majors.value = majorsRes.data?.data || [];
    categories.value = categoriesRes.data?.data || [];

    fetchQuestions();
  } catch (error) {
    ElMessage.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 计算属性：根据选择的专业筛选分类
const filteredCategories = computed(() => {
  if (!filters.majorId) return [];
  return categories.value.filter(c => c.majorId === filters.majorId);
});

// 题目类型映射
const typeMap = {
  fill_in: '填空题',
  choice: '选择题'
};

// 标签类型映射
const typeTagMap = {
  fill_in: 'warning',
  choice: 'primary'
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 获取题目数据
// const fetchQuestions = async () => {
//   try {
//     loading.value = true;
//     const params = {
//       pageNum: pagination.currentPage,
//       pageSize: pagination.pageSize,
//       majorId: filters.majorId,
//       keyword: filters.keyword,
//       questionType: filters.questionType,
//       categoryId: filters.categoryId,
//     };
//
//     const response = await axios.get('/admin/manage/questions', { params });
//     const pageInfo = response.data.data;
//
//     // 更新分页数据
//     pagination.total = pageInfo.total;
//     pagination.currentPage = pageInfo.pageNum;
//     pagination.pageSize = pageInfo.pageSize;
//
//     // 更新题目列表
//     questions.value = pageInfo.list.map(q => ({
//       ...q,
//       creator: q.creator || userStore.userInfo?.username || '未知用户',
//       categoryName: q.categoryName ||
//           categories.value.find(c => c.categoryId === q.categoryId)?.categoryName || '未知分类',
//       majorName: q.majorName ||
//           majors.value.find(m => m.majorId === q.majorId)?.majorName || '未知专业'
//     }));
//
//   } catch (error) {
//     console.error('获取题目失败:', error);
//     if (error.response) {
//       ElMessage.error(`加载失败: ${error.response.data.message || error.response.status}`);
//     } else {
//       ElMessage.error('网络错误或服务器无响应');
//     }
//   } finally {
//     loading.value = false;
//   }
// };
const fetchQuestions = async () => {
  try {
    loading.value = true;
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      majorId: filters.majorId,
      keyword: filters.keyword,
      questionType: filters.questionType,
      categoryId: filters.categoryId,
    };

    const response = await axios.get('/admin/manage/questions/page', { params });
    const pageResult = response.data.data;

    // 修正分页数据处理
    pagination.total = pageResult.total;
    // 删除下面两行错误的赋值
    // pagination.currentPage = pageResult.currentPage;
    // pagination.pageSize = pageResult.pageSize;

    // 保留当前分页设置（前端维护分页状态）
    // pagination.currentPage 保持不变
    // pagination.pageSize 保持不变

    // 更新题目列表
    questions.value = pageResult.records.map(q => ({
      ...q,
      creator: q.creator || userStore.userInfo?.username || '未知用户',
      categoryName: q.categoryName ||
          categories.value.find(c => c.categoryId === q.categoryId)?.categoryName || '未知分类',
      majorName: q.majorName ||
          majors.value.find(m => m.majorId === q.majorId)?.majorName || '未知专业'
    }));

  } catch (error) {
    console.error('获取题目失败:', error);
    if (error.response) {
      ElMessage.error(`加载失败: ${error.response.data.message || error.response.status}`);
    } else {
      ElMessage.error('网络错误或服务器无响应');
    }
  } finally {
    loading.value = false;
  }
};

// 初始化数据
onMounted(async () => {
  await fetchMajors();
  await fetchAllCategories();
  fetchQuestions();
  onMounted(loadInitialData);
});

// 搜索题目
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchQuestions();
};

// 专业变更处理
const handleMajorChange = (majorId) => {
  filters.majorId = majorId ? Number(majorId) : null;
  filters.categoryId = null;

  // 确保使用 majorId 字段过滤
  filteredCategories.value = majorId
      ? categories.value.filter(c => c.majorId === majorId)
      : [];

  handleSearch();
};

// 表单专业变更处理
const handleFormMajorChange = async (majorId) => {
  formData.majorId = majorId ? Number(majorId) : null;
  formData.categoryId = null; // 重置分类选择

  if (majorId) {
    try {
      const response = await axios.get(`/admin/manage/categories/by-major/${majorId}`);
      formCategories.value = response.data.data || [];
    } catch (error) {
      console.error('加载分类失败:', error);
      ElMessage.error('加载分类数据失败');
      formCategories.value = [];
    }
  } else {
    formCategories.value = [];
  }
};

// 显示添加对话框
const showAddDialog = () => {
  isEditing.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 显示编辑对话框
const showEditDialog = async (question) => {
  try {
    loading.value = true;
    isEditing.value = true;
    editingQuestionId.value = question.questionId;

    // 获取题目详情
    const response = await axios.get(`/admin/manage/questions/${question.questionId}`);
    const fullQuestion = response.data.data;
    currentQuestion.value = { ...fullQuestion };

    // 处理选项内容（移除已有前缀）
    const processedChoices = fullQuestion.choices?.map(choice => ({
      ...choice,
      choiceContent: choice.choiceContent.replace(/^[A-Z]\.\s*/, '')
    })) || [];

    // 填充表单数据 - 重点修改专业和分类的处理
    Object.assign(formData, {
      questionType: fullQuestion.questionType,
      content: fullQuestion.content,
      baseScore: fullQuestion.baseScore,
      weight: fullQuestion.weight,
      createdBy: fullQuestion.createdBy,
      // 从分类中获取专业ID
      majorId: fullQuestion.majorId ? Number(fullQuestion.majorId) : null,
      categoryId: fullQuestion.categoryId ? Number(fullQuestion.categoryId) : null,
      choices: fullQuestion.questionType === 'choice' ?
          (fullQuestion.choices || []) : [],
      blanks: fullQuestion.questionType === 'fill_in' ?
          (fullQuestion.blanks || []) : []
    });

    // 根据专业ID加载对应的分类
    if (formData.majorId) {
      const categoriesRes = await axios.get(`/admin/manage/categories/by-major/${formData.majorId}`);
      formCategories.value = categoriesRes.data.data || [];
    } else {
      formCategories.value = [];
    }

    // 设置正确答案（选择题）
    if (fullQuestion.questionType === 'choice' && fullQuestion.choices) {
      formData.answer = fullQuestion.choices
          .map((choice, index) => choice.isCorrect ? String.fromCharCode(65 + index) : null)
          .filter(Boolean);
    }

    dialogVisible.value = true;
  } catch (error) {
    console.error('获取题目详情失败:', error);
    ElMessage.error('获取题目详情失败');
  } finally {
    loading.value = false;
  }
};

// 显示详情对话框
const showDetailDialog = async (question) => {
  try {
    loading.value = true;
    const response = await axios.get(`/admin/manage/questions/${question.questionId}`);
    currentQuestion.value = response.data.data;

    detailDialogVisible.value = true;
  } catch (error) {
    console.error('获取题目详情失败:', error);
    ElMessage.error('获取题目详情失败');
  } finally {
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  editingQuestionId.value = null;
  Object.assign(formData, {
    questionType: 'choice',
    content: '',
    answer: [],
    baseScore: 10,
    weight: 1.0,
    createdBy: null,
    majorId: null,
    categoryId: null,
    choices: [
      { choiceContent: '', isCorrect: false },
      { choiceContent: '', isCorrect: false }
    ],
    blanks: [
      { answer: '', maxLength: 20 }
    ]
  });
  formCategories.value = [];
};

// 添加选项
const addChoice = () => {
  formData.choices.push({ choiceContent: '', isCorrect: false });
};

// 删除选项
const removeChoice = (index) => {
  if (formData.choices.length <= 2) {
    ElMessage.warning('至少需要两个选项');
    return;
  }

  formData.choices.splice(index, 1);

  // 重新计算正确答案
  formData.answer = formData.answer
      .filter(ans => ans.charCodeAt(0) !== 65 + index)
      .map(ans => {
        const charCode = ans.charCodeAt(0);
        return charCode > 65 + index ?
            String.fromCharCode(charCode - 1) : ans;
      });
};

// 添加空位
const addBlank = () => {
  formData.blanks.push({ answer: '', maxLength: 20 });
};

// 删除空位
const removeBlank = (index) => {
  if (formData.blanks.length <= 1) {
    ElMessage.warning('至少需要一个空位');
    return;
  }
  formData.blanks.splice(index, 1);
};

// 题目类型变化处理
const handleQuestionTypeChange = (type) => {
  if (type === 'choice') formData.answer = [];
};

const fetchAllCategories = async () => {
  try {
    const response = await axios.get('/admin/manage/categories');
    categories.value = response.data.data;
  } catch (error) {
    console.error('获取分类失败:', error);
    ElMessage.error('加载分类数据失败');
    categories.value = [];
  }
};

// const fetchCategories = async () => {
//   try {
//     // 使用POST请求并传递JSON参数
//     const categoriesRes = await axios.post('/admin/manage/categories', {
//       pageNum: 1,
//       pageSize: 1000,
//       keyword: '',
//       userId: userStore.userInfo?.userId || ''
//     }, {
//       headers: {
//         'Content-Type': 'application/json'
//       }
//     });
//
//     // 确保正确获取数据
//     categories.value = categoriesRes.data?.data?.list || [];
//   } catch (error) {
//     console.error('获取分类失败:', error);
//
//     let errorMessage = '加载分类数据失败';
//     if (error.response) {
//       errorMessage += `: ${error.response.data?.message || error.response.status}`;
//     } else {
//       errorMessage += `: ${error.message}`;
//     }
//
//     ElMessage.error(errorMessage);
//     categories.value = [];
//   }
// };

const fetchMajors = async () => {
  try {
    // 修改为GET请求
    const majorsRes = await axios.get('/admin/manage/majors');
    // 调整数据结构处理
    majors.value = majorsRes.data?.data || []; // 直接获取数组
  } catch (error) {
    console.error('获取专业失败:', error);
    ElMessage.error('加载专业数据失败');
    majors.value = [];
  }
};

// 提交表单（添加/编辑）
const submitForm = async () => {
  try {
    const userId = userStore.userInfo?.userId;
    if (!userId) {
      ElMessage.error('无法获取用户信息，请重新登录');
      return;
    }

    // 准备基础数据
    const requestData = {
      questionId: editingQuestionId.value,
      questionType: formData.questionType,
      content: formData.content,
      baseScore: formData.baseScore,
      weight: formData.weight,
      createdBy: userId,
      // 只传递分类ID
      categoryId: formData.categoryId,
      // 不传递专业ID
    };

    // 处理选择题选项
    // if (formData.questionType === 'choice') {
    //   requestData.choices = formData.choices.map((choice, index) => ({
    //     // choiceContent: choice.choiceContent,
    //
    //     // 自动添加字母前缀 (A., B., C., ...)
    //     choiceContent: `${String.fromCharCode(65 + index)}. ${choice.choiceContent}`,
    //
    //     // 修改点：仅在添加题目时添加前缀
    //     // choiceContent: isEditing.value ?
    //     //     choice.choiceContent :  // 编辑时直接使用原始内容
    //     //     `${String.fromCharCode(65 + index)}. ${choice.choiceContent}`,  // 添加时添加前缀
    //
    //     isCorrect: formData.answer.includes(String.fromCharCode(65 + index))
    //   }));
    // }
    if (formData.questionType === 'choice') {
      requestData.choices = formData.choices.map((choice, index) => {
        // 编辑时移除可能存在的旧前缀
        const cleanContent = isEditing.value
            ? choice.choiceContent.replace(/^[A-Z]\.\s*/, '')
            : choice.choiceContent;

        return {
          choiceId: choice.choiceId,  // 保留选项ID用于更新
          choiceContent: `${String.fromCharCode(65 + index)}. ${cleanContent}`,
          isCorrect: formData.answer.includes(String.fromCharCode(65 + index))
        };
      });
    }
    // 处理填空题空位
    else if (formData.questionType === 'fill_in') {
      requestData.blanks = formData.blanks.map((blank, index) => ({
        answer: blank.answer,
        maxLength: blank.maxLength,
        blankIndex: index + 1
      }));
    }

    // 根据操作类型发送请求
    if (isEditing.value) {
      await axios.put(
          `/admin/manage/questions/${editingQuestionId.value}`,
          requestData
      );
    } else {
      await axios.post('/admin/manage/questions', requestData);
    }

    ElMessage.success(isEditing.value ? '题目更新成功' : '题目添加成功');
    dialogVisible.value = false;
    fetchQuestions();
  } catch (error) {
    console.error('操作失败:', error);

    let errorMessage = '操作失败，请检查网络或联系管理员';
    if (error.response?.data?.message) {
      errorMessage = `操作失败: ${error.response.data.message}`;
    }

    ElMessage.error(errorMessage);
  }
};

// 删除题目
const handleDelete = async (questionId) => {
  try {
    await ElMessageBox.confirm('确定要删除这道题目吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await axios.delete(`/admin/manage/questions/${questionId}`);
    ElMessage.success('题目删除成功');
    fetchQuestions();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除题目失败');
    }
  }
};
</script>

<style scoped>
.question-manage {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  align-items: center;
}

.content-preview {
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.question-detail {
  padding: 10px 20px;
}

.detail-item {
  margin-bottom: 15px;
}

.detail-row {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
}

.detail-item .label {
  display: inline-block;
  width: 100px;
  font-weight: bold;
  color: #606266;
}

.detail-item .value {
  color: #303133;
}

.detail-item .content,
.detail-item .answer {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-top: 5px;
  white-space: pre-wrap;
}

/* 新增样式 */
.choice-item, .blank-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.choice-input, .blank-input {
  flex: 1;
}

.choice-actions {
  min-width: 120px;
}

.max-length {
  display: flex;
  align-items: center;
  min-width: 150px;
}

.max-length span {
  white-space: nowrap;
  margin-right: 5px;
}

.delete-btn {
  flex-shrink: 0;
}

.choice-count, .blank-count {
  margin-left: 10px;
  color: #909399;
}

.option-item, .blank-info {
  margin-bottom: 10px;
  padding: 8px;
  background: #f5f7fa;
  border-radius: 4px;
}

.option-tag, .blank-tag {
  margin-top: 5px;
}

.option-letter {
  font-weight: bold;
}

.blank-label {
  font-weight: bold;
}
</style>